package edu.tongji.jiaowu.webapp.action.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tongji.quickCRUDQ.define.Column;
import com.tongji.quickCRUDQ.define.Row;
import com.tongji.quickCRUDQ.define.Table;
import com.tongji.quickCRUDQ.exception.FormatException;
import com.tongji.quickCRUDQ.html.Select;
import com.tongji.quickCRUDQ.model.CommonBean;
import com.tongji.quickCRUDQ.util.Option;
import com.tongji.quickCRUDQ.webapp.handler.QuickHandler;

import edu.tongji.jiaowu.service.OriginalScoreCourseManager;
import edu.tongji.jiaowu.service.OriginalScoreManager;

public class OriginalScoreHandler extends HandlerInterceptorAdapter implements QuickHandler {
    private OriginalScoreCourseManager originalScoreCourseManager;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
    	Map quickMap=(Map)request.getAttribute("quickMap");
    	Row   row  =(Row)  quickMap.get("row");
    	Table table=(Table)quickMap.get("table");
    	String scoreCourseId=request.getParameter("REFID");
    	CommonBean scoreCourse=originalScoreCourseManager.findOriginalScoreCourseById(scoreCourseId);
    	if (scoreCourse.getSize()!=1) {
			throw new FormatException("无此原始成绩课程id("+scoreCourseId+")");
		}
    	String scoreFormat=scoreCourse.getPropertyAsString(0, "scoreFormat");
    	
    	Column scoreColumn1=row.findColumn("SCORE", table.getTablename());
    	Column scoreColumn2=row.findColumn("SCORE2", table.getTablename());
    	if ("02".equals(scoreFormat)) {//百分制
			if (scoreColumn1!=null) {
				scoreColumn1.setHtmltype("Text");
			}
			if (scoreColumn2!=null) {
				scoreColumn2.setHtmltype("Text");
			}
		}else if("03".equals(scoreFormat)){//二级制(及格、不及格)
			if (scoreColumn1!=null) {
				rebuild(scoreColumn1);
			}
			if (scoreColumn2!=null) {
				rebuild(scoreColumn2);
			}
		} 
		return super.preHandle(request, response, object);
	}

	private void rebuild(Column scoreColumn) {
		Select select=(Select) scoreColumn.getControl();
		List options=select.getOptions();
		List twoLevels=new ArrayList();
		for (int i = 0; i < options.size(); i++) {
			Option opt=(Option) options.get(i);
			String key = opt.getKey();
			//TODO mytodo--硬编码成绩及格(-4)、不及格(-5)
			if ("-4".equals(key)||"-5".equals(key)) {//及格、不及格
				twoLevels.add(opt);
			}
		}
		select.setOptions(twoLevels);
	}

	public OriginalScoreCourseManager getOriginalScoreCourseManager() {
		return originalScoreCourseManager;
	}

	public void setOriginalScoreCourseManager(OriginalScoreCourseManager originalScoreCourseManager) {
		this.originalScoreCourseManager = originalScoreCourseManager;
	}
	
}
